package cn.silver.framework.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import cn.silver.framework.mybatis.domain.BaseEntity;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import cn.silver.framework.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

/**
 * MP注入处理器
 *
 * @author  Silver.Zhou
 */
@Slf4j
public class InjectionMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity entity) {
               entity.preInsert();
            }
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.HTTP_UNAUTHORIZED, "自动注入异常 => " + e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity entity) {
                entity.preUpdate();
            }
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.HTTP_UNAUTHORIZED, "自动注入异常 => " + e.getMessage());
        }
    }
}
